package com.eimf.saf.test;

import java.io.File;
import java.io.FilenameFilter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import org.apache.struts2.StrutsSpringTestCase;
import org.springframework.test.context.support.GenericXmlContextLoader;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author eden
 * @date 2013-12-28 上午10:37:03
 * @Description: TODO(这里用一句话描述这个类的作用)
 */
public class SpringBeanFactoryMock extends StrutsSpringTestCase
{

    @Override
    public void setUp() throws Exception
    {
        super.setUp();
    }

    @Override
    protected void setupBeforeInitDispatcher() throws Exception
    {
        final GenericXmlContextLoader xmlContextLoader = new GenericXmlContextLoader();
        StrutsSpringTestCase.applicationContext = xmlContextLoader.loadContext(getContextLocation());
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                StrutsSpringTestCase.applicationContext);
    }

    public String getConfigPathWork()
    {
        final URL classUrl = SpringBeanFactoryMock.class.getResource("");
        String path = classUrl.getPath();
        try
        {
            path = URLDecoder.decode(path, "UTF-8");
        } catch (final UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return path;
    }

    public String[] getContextLocation()
    {
        // String path = getConfigPathWork();
        // path = path.substring(1, path.indexOf("WEB-INF")) + "WEB-INF/";
        final String path = "F://googlecode/SAF/src/";
        final File configPath = new File(path);
        final String[] applicationContexts = configPath.list(new FilenameFilter()
        {
            @Override
            public boolean accept(final File dir, final String name)
            {
                if (name.toLowerCase().startsWith("applicationcontext"))
                {
                    return true;
                }
                return false;
            }
        });
        for (int i = 0; i < applicationContexts.length; i++)
        {
            applicationContexts[i] = "file:" + path + applicationContexts[i];
        }
        return applicationContexts;
    }
}
